/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package edu.scs.ubbcluj.model;

import edu.scs.ubbcluj.backend.MongoDB;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 *
 * @author Torok
 */
public class Database implements Model{
    private static final String TYPE = "DB";
    private String name;
    private List<Table> tables;
    
    
    public Database(String name) {
        this.name = name;
        tables = new ArrayList();
    }

    
    public List<Table> getTables() {
        return tables;
    }
    
    public List<String> getTablesName() {
        List<String> nameList = new ArrayList();
        Iterator<Table> iterator = tables.iterator();
	while (iterator.hasNext()) {
		nameList.add(iterator.next().getName());
	}
        return nameList;
    }
    
    public void addTable(Table table){
        tables.add(table);
    }
    
    public void removeTable(Table table){
        tables.remove(table);
    }

    public void setTables(List<Table> tables) {
        this.tables = tables;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    
    public String checkForeignKeyReference(Table curentTable, List<String> row) {
        for(Table otherTable : tables) {
            for(Attribute attr : curentTable.getPrimaryKeys()) {
                for(ForeignKey fk : otherTable.getForeignKeys())
                    if(fk.getName().equals(attr.getName())) {
                        int ind = curentTable.getPrimaryKeys().indexOf(attr);
                        if(otherTable.checkIfFkExistsInTable(fk, row.get(ind), ind))
                            return row.get(ind) + " is referenced in table " + otherTable.getName() + ". It can not be deleted.";
                    }
            } 
        }
        return null;
    }
    
    public List<Attribute> searchForForeignKeys(Table table) {
        List<Attribute> ret = new ArrayList();
        for(Table t : tables) {
            for(Attribute attr : table.getPrimaryKeys()) {
                for(ForeignKey fk : t.getForeignKeys())
                    if(fk.getName().equals(attr.getName()))
                        ret.add(attr);
            }
        }
        return ret;
    }

    @Override
    public String toString() {
        return this.name;
    }

    @Override
    public String getType() {
       return TYPE;
    }
    
}
